package com.kalenchuk.service.impl;

import java.util.List;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kalenchuk.dao.WireDao;
import com.kalenchuk.model.Wire;
import com.kalenchuk.service.WireService;
import com.kalenchuk.util.Utils;

@Service("wireService")
@Transactional
public class WireServiceImpl implements WireService {

	@Autowired
	private WireDao wireDao;

	
	public void fillWireTable(JTable table) {
		List<Wire> wires = wireDao.findAll();
		if(Utils.isCollectionNotEmpty(wires)) {
			DefaultTableModel model = (DefaultTableModel) table.getModel();
			for (int i = 0; i < model.getRowCount(); i++) {
				model.removeRow(i);
			}

			for (Wire wire : wires) {
				model.addRow(new Object[] { wire.getBrand(),
						wire.getActiveResistance(), wire.getReactResistance(),
						wire.getMaxCurrentValue(), wire.getId() });
			}
		}
		
	}
	
	
	public void updateWire(Long id, String brand, Double aR, Double rR, Double current) {
		Wire wire = wireDao.findById(id);
		wire.setBrand(brand);
		wire.setActiveResistance(aR);
		wire.setReactResistance(rR);
		wire.setMaxCurrentValue(current);
		wireDao.merge(wire);
		
	}
	
	@Transactional
	public Long saveWire(String brand, Double aR, Double rR, Double current) {
		Wire wire = new Wire();
		wire.setBrand(brand);
		wire.setActiveResistance(aR);
		wire.setReactResistance(rR);
		wire.setMaxCurrentValue(current);
		wireDao.save(wire);
		return wire.getId();	
	}
	
	@Transactional
	public void deleteWire(Wire wire) {
		wireDao.delete(wire);
	}
	
	@Transactional
	public void deleteWire(Long wireId) {
		Wire wire = wireDao.findById(wireId);
		wireDao.delete(wire);
	}
	
}
